package com.jingogo.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jingogo.common.BusinessException;
import com.jingogo.entity.Order;
import com.jingogo.mapper.OrderMapper;
import com.jingogo.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createOrder(Order order) {
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        super.save(order);
        return order.getOrderNo();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handlePaymentCallback(String orderNo, String payStatus, String payTime, String transactionId) {
        Order order = super.lambdaQuery().eq(Order::getOrderNo, orderNo).one();
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        order.setPayStatus(Integer.parseInt(payStatus));
        super.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelTimeoutOrders() {
        // 实现超时取消订单逻辑，实际应有定时任务扫描超时订单
        return 0;
    }

    @Override
    public Order getOrderByNo(String orderNo) {
        return super.lambdaQuery().eq(Order::getOrderNo, orderNo).one();
    }

    @Override
    public IPage<Order> getUserOrders(Long userId, Integer pageNum, Integer pageSize, String status) {
        Page<Order> page = new Page<>(pageNum, pageSize);
        return super.lambdaQuery()
                .eq(Order::getUserId, userId)
                .eq(status != null, Order::getOrderStatus, status)
                .page(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderStatus(String orderNo, String status) {
        Order order = super.lambdaQuery().eq(Order::getOrderNo, orderNo).one();
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        order.setOrderStatus(Integer.parseInt(status));
        super.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payWithWallet(String orderNo, Long userId) {
        Order order = super.lambdaQuery().eq(Order::getOrderNo, orderNo).one();
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        order.setPayStatus(1);
        super.updateById(order);
    }
}
